<template>
  <div class="padding flex height-100 content-with-tree">
    <div class="left-tree">
      <div class="flex info-title p-3">
        <span>字典分组</span>
        <el-tooltip content="新增分组" v-if="isEmpty">
          <i class="el-icon-plus" style="margin-left: auto;" @click="addGroup"></i>
        </el-tooltip>
      </div>
      <div class="padding-10 keyword-filter">
        <el-input v-model="keyword" placeholder="关键字" clearable></el-input>
      </div>
      <el-scrollbar style="height: calc(100% - 110px)" wrap-style="overflow-x: hidden;">
        <el-tree
          ref="tree"
          default-expand-all
          highlight-current
          :expand-on-click-node="false"
          :data="treeData"
          :props="{
            label: 'dicName',
            children: 'children',
            isLeaf: 'isLeaf'
          }"
          :filter-node-method="filterNodeMethod"
          @node-click="onNodeClick"
          @node-contextmenu="onContextmenu"
        ></el-tree>
      </el-scrollbar>
      <ul v-show="visible" v-click-outside="onClickOutside" class="context-menu" :style="{left: left + 'px', top: top + 'px'}">
        <li class="context-menu-item" @click="addGroup">添加分组</li>
        <li class="context-menu-item" @click="editGroup">编辑分组</li>
        <li class="context-menu-item" @click="delGroup">删除分组</li>
      </ul>
    </div>
    <div class="flex direction-column height-100 right-content">
      <div class="info-title pt pb-3">数据列表</div>
      <div class="button-group">
        <el-button type="primary" @click="add">新增</el-button>
      </div>
      <div class="flex-1 overflow-auto dark-table-wrapper">
        <el-table
           v-loading="loading" :data="lists"
          height="100%"
          :header-cell-style="{
            backgroundColor: themeColor,
            color: 'white'
          }"
        >
          <div slot="empty" class="empty-lists">
            <i class="i-custom:search"></i>
            <span class="empty-text">暂无数据</span>
          </div>
          <el-table-column v-for="column in columns" :key="column.prop" v-bind="column"></el-table-column>
          <el-table-column label="操作" prop="id" width="120px" align="center">
            <template #default="{ row }">
              <td-button title="编辑" @click="edit(row)">
                <i class="i-custom:editor"></i>
              </td-button>
              <td-button
                title="删除"
                class="del-btn"
                icon-style="color: var(--danger-color);border-color: var(--danger-color);"
                @click="del(row)"
              >
                <i class="i-custom:ashbin"></i>
              </td-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <group-operate-modal
      ref="groupModal" :modal-title="groupTitle" :data="groupData"
      @save-success="onGroupSuccess"
    ></group-operate-modal>
    <dict-operate-modal
      ref="dictModal" :modal-title="dictTitle" :data="dictData"
      @save-success="onDictSuccess"
    ></dict-operate-modal>
  </div>
</template>

<script>
import { queryTreeList, delGroup, saveOrUpdateDictionaryGroup } from '@/api/sysDictionaryGroup'
import { loadDicCodeByDictionaryEncoList, delCode, saveOrUpdateDictionaryEnco } from '@/api/sysDictionaryEnco'
import TdButton from '@/components/td-button'
import GroupOperateModal from './group-operate-modal'
import DictOperateModal from './dict-operate-modal'
import { confirmDel } from '@/utils'

const api = {
  queryTreeList,
  delGroup,
  saveOrUpdateDictionaryGroup,
  loadDicCodeByDictionaryEncoList,
  delCode,
  saveOrUpdateDictionaryEnco
}
export default {
  name: 'data-dictionary',
  components: {
    TdButton,
    GroupOperateModal,
    DictOperateModal
  },
  data () {
    return {
      keyword: '',
      loading: false,
      lists: [],
      columns: [
        { label: 'ID', prop: 'id' },
        { label: '字典编码', prop: 'dicCode' },
        { label: '字典KEY', prop: 'dicKey' },
        { label: '字典VALUE', prop: 'dicValue' }
      ],
      treeData: [],
      currentCode: '',
      visible: false,
      top: 0,
      left: 0,
      currentNodeData: null,

      groupTitle: '',
      groupData: {},

      dictTitle: '',
      dictData: {}
    }
  },
  computed: {
    isEmpty () {
      return this.treeData.length === 0
    },
    themeColor () {
      return this.$store.state.user.theme
    }
  },
  watch: {
    keyword (val) {
      this.$refs.tree.filter(val)
    }
  },
  mounted () {
    this.getTreeData()
  },
  methods: {
    getLists () {
      this.loading = true
      return api.loadDicCodeByDictionaryEncoList(this.currentCode).then(res => {
        if (res.code === 200) {
          this.lists = res.data
        }
      }).finally(() => {
        this.loading = false
      })
    },
    getTreeData () {
      return api.queryTreeList().then(res => {
        if (res.code === 200) {
          res.data.forEach(v => {
            v.isLeaf = !!(v.children && v.children.length > 0)
          })
          this.treeData = res.data
        }
      })
    },
    filterNodeMethod (value, data) {
      if (!value) return true
      return data.dicName.indexOf(value) > -1
    },
    onContextmenu (evt, data) {
      const minWidth = 105
      const $el = this.$refs.tree.$el
      const bounding = $el.getBoundingClientRect()
      const offsetLeft = bounding.left
      const offsetTop = bounding.top
      const offsetWidth = $el.offsetWidth
      const maxLeft = offsetWidth - minWidth
      const left = evt.clientX - offsetLeft + 15
      const top = evt.clientY - offsetTop + 30

      if (left > maxLeft) {
        this.left = maxLeft
      } else {
        this.left = left
      }

      this.top = top
      this.visible = true
      this.currentNodeData = data
    },
    onClickOutside () {
      this.visible = false
    },
    onGroupSuccess () {
      this.getTreeData()
    },
    onDictSuccess () {
      this.getLists()
    },
    addGroup () {
      const current = this.currentNodeData || {}
      this.groupTitle = '添加分组'
      this.groupData = {
        superiorId: current.id || '0',
        superiorName: current.dicName || '',
        dicName: '',
        dicCode: ''
      }
      this.$nextTick(() => {
        this.visible = false
        this.$refs.groupModal.open()
      })
    },
    editGroup () {
      const current = this.currentNodeData
      this.groupTitle = '编辑分组'
      this.groupData = {
        id: current.id,
        superiorId: current.superiorId,
        superiorName: current.superiorName,
        dicName: current.dicName,
        dicCode: current.dicCode
      }
      this.$nextTick(() => {
        this.visible = false
        this.$refs.groupModal.open()
      })
    },
    delGroup () {
      this.visible = false
      const current = this.currentNodeData
      return api.delGroup(current.id).then(res => {
        if (res.code === 200) {
          this.$message.success('删除成功')
          this.getTreeData()
        }
      })
    },
    add () {
      const currentCode = this.currentCode
      if (!currentCode) {
        return this.$message.error('请选择字典')
      }
      this.dictTitle = '添加字典数据'
      this.dictData = {
        id: '',
        dicCode: currentCode,
        dicKey: '',
        dicValue: ''
      }
      this.$nextTick(() => {
        this.$refs.dictModal.open()
      })
    },
    edit (row) {
      this.dictTitle = '编辑字典数据'
      this.dictData = {
        id: row.id,
        dicCode: row.dicCode,
        dicKey: row.dicKey,
        dicValue: row.dicValue
      }
      this.$nextTick(() => {
        this.$refs.dictModal.open()
      })
    },
    del (row) {
      confirmDel(this).then(() => {
        api.delCode(row.id).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功')
            this.getLists()
          }
        })
      }).catch(() => {})
    },
    onNodeClick (data) {
      const isLeaf = !(data.children && data.children.length > 0)
      if (isLeaf) {
        this.currentCode = data.dicCode
        if (this.currentCode) {
          this.$nextTick(() => {
            this.getLists()
          })
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  .left-tree {
    position: relative;
  }
  .context-menu {
    position: absolute;
    background: white;
    box-shadow: 0 0 10px rgba(0,0,0,0.125);
    list-style: none;
    padding-left: 0;
    border-radius: 6px;
  }
  .context-menu-item {
    padding: 8px 16px;
    font-size: 12px;
    cursor: default;
  }
</style>
